package com.weijian.controller.admin;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.weijian.common.BaseContext;
import com.weijian.common.exception.ServiceException;
import com.weijian.dal.dto.AddressDTO;
import com.weijian.dal.entity.Address;
import com.weijian.service.AddressService;
import io.swagger.v3.oas.annotations.Operation;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;


@RestController
@RequestMapping("/addresses")
@RequiredArgsConstructor
public class AddressController {

    private final AddressService addressService;

    @Operation(summary = "根据id查询地址")
    @GetMapping("{addressId}")
    public Address findAddressById(@PathVariable("addressId") Long id) {
        // 1.根据id查询
        Address address = addressService.getById(id);
        //2.判断当前用户
        Long userId = BaseContext.getCurrentId();
        if (!address.getUserId().equals(userId)) {
            throw new ServiceException(401, "地址不属于当前登录用户");
        }
        return address;
    }

    @Operation(summary = "查询当前用户地址列表")
    @GetMapping
    public List<AddressDTO> findMyAddresses() {
        // 1.查询列表
        List<Address> list = addressService.query().eq("user_id", BaseContext.getCurrentId()).list();
        // 2.判空
        if (CollUtil.isEmpty(list)) {
            return new ArrayList<>();
        }
        // 3.转vo
        return BeanUtil.copyToList(list, AddressDTO.class);
    }
}
